package leetcode.solution;

import leetcode.struct.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by tanlee on 2016/5/2.
 */
public class UniqueBinarySearchTrees {
    public List<TreeNode> generateTrees(int n) {
        List<TreeNode> resultTreeList = new ArrayList<TreeNode>();
        if(n == 0){
            return resultTreeList;
        }
        return createTrees(1,n);
    }

    private List<TreeNode> createTrees(int start,int end){
        List<TreeNode> resultTreeList = new ArrayList<TreeNode>();
        if(start > end){
            resultTreeList.add(null);
            return resultTreeList;
        }
        if(start == end){
            resultTreeList.add(new TreeNode(start));
            return resultTreeList;
        }
        resultTreeList = new ArrayList<TreeNode>();
        for(int i=start;i<=end;i++){
            List<TreeNode> leftList = createTrees(start,i-1);
            List<TreeNode> rightList = createTrees(i+1,end);
            for(int j=0;j<leftList.size();j++){
                for(int k=0;k<rightList.size();k++){
                    TreeNode root = new TreeNode(i);
                    root.left = leftList.get(j);
                    root.right = rightList.get(k);
                    resultTreeList.add(root);
                }
            }
        }
        return resultTreeList;
    }

}
